import os
import shutil
import re
import zipfile

SUFFIXES = {
    1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}


imgType_list = {'jpg','bmp','png','jpeg','rgb','tif'}


def approximate_size(size, a_kilobyte_is_1024_bytes=True):
    '''Convert a file size to human-readable form.

    Keyword arguments:
    size -- file size in bytes
    a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
                                if False, use multiples of 1000

    Returns: string

    '''
    if size < 0:
        raise ValueError('number must be non-negative')

    multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
    for suffix in SUFFIXES[multiple]:
        size /= multiple
        if size < multiple:
            return '{0:.1f} {1}'.format(size, suffix)

    raise ValueError('number too large')


def un_zip(zip_file, des_dir, timestamp=None):
    """
    filename: 压缩文件路径
    root: 解压文件夹路径
    """
    os.makedirs(des_dir, exist_ok=True)

    with zipfile.ZipFile(zip_file) as file:
        file.extractall(des_dir)

    # # 原文件名
    # folder_name = os.path.splitext(os.path.basename(zip_file))[0]

    # new_folder_name = folder_name + "-" + timestamp
    
    # original_directory_path = os.path.join(des_dir, folder_name)
    # extracted_directory_path = os.path.join(des_dir, new_folder_name)

    # # 重命名压缩文件
    # os.rename(original_directory_path, extracted_directory_path)


def unzip_lot(zip_dir, des_dir, timestamp=None):
    """
    filename: 压缩文件路径
    root: 解压文件夹路径
    """
    remkdir(des_dir)

    for file in os.listdir(zip_dir):
        zip_file = os.path.join(zip_dir, file)
        un_zip(zip_file, des_dir)


def rm_dir(dir_path):
    if os.path.exists(dir_path):
        shutil.rmtree(dir_path)
    os.mkdir(dir_path)


def remkdir(dir_path):
    if os.path.exists(dir_path):
        shutil.rmtree(dir_path)

    os.makedirs(dir_path)


def rm_file(file_path):
    if os.path.exists(file_path):
        os.remove(file_path)


def rename_pmi(wafer_dir, image_name):
    pattern = r'[^a-zA-Z0-9.]'  # 匹配非数字、非英文字母和非句点的字符
    new_filename = re.sub(pattern, '.', image_name)
    new_filepath = os.path.join(wafer_dir, new_filename)

    os.rename(os.path.join(wafer_dir, image_name), new_filepath)

    return new_filename
